package business;
import cn.hutool.cache.CacheUtil;
import cn.hutool.cache.impl.TimedCache;
import cn.hutool.core.util.StrUtil;
import models.cms_channel;
import models.cms_news;
import org.apache.commons.lang.StringUtils;
import play.Logger;
import utils.PageBean;
import java.util.List;
import java.util.UUID;

public class ApiService {
    private static  String prefix_token = "api_uid_";
    static TimedCache<String, String> cache = CacheUtil.newTimedCache(24 * 60 * 60 * 1000);  // 默认缓存24小时
    public static String getToken(String uid){
        String token = "";
        token = UUID.randomUUID().toString().replace("-","");
        Logger.info(token);
        cache.put(prefix_token+ uid, token);
        return token;
    }
    public static boolean deleteToken(String uid,String token){
        if(isLoginByApi(uid,token)){
            cache.remove(prefix_token+uid);
            return true;
        }
        return false;
    }
    public static boolean isLoginByApi(String uid,String token){
        Object object = cache.get(prefix_token + uid);
        if(null !=object && object.toString().equals(token)){
            return true;
        }else{
            return false;
        }
    }
    public static List<cms_channel> getChannelList(){
        return cms_channel.find(" from cms_channel where pid=0").fetch();
    }
    public static PageBean<cms_news> getNewsList(String title,long channel_id){
        StringBuilder sql = new StringBuilder();
        StringBuilder sqlCount = new StringBuilder();
        String sqlAppend = " where 1=1 ";
        if(!StringUtils.isEmpty(title)){
            title = StrUtil.sub(title,0,100);
            sqlAppend += " and title like '%"+title+"%' ";
        }
        if(channel_id!=0){
            sqlAppend += " and channel_id=" + channel_id;
        }
        sql.append(" select * from cms_news ").append(sqlAppend);
        sql.append(" order by id desc ");
        sqlCount.append(" select count(*) from cms_news ").append(sqlAppend);
        PageBean<cms_news> pageBean = new BaseBiz<cms_news>().queryList(cms_news.class,sql,sqlCount);
        Logger.info(pageBean.page.size()+"");
        return pageBean;
    }
}
